<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <script>
    // function throttle(func, wait) {
    //   let timeStamp = 0;

    //   return function (...args) {
    //     const context = this;

    //     const now = Date.now();
    //     const elapsed = now - timeStamp;
    //     if (elapsed >= wait) {
    //       func.apply(context, args);
    //       timeStamp = now;
    //     }
    //   };
    // }

    // 结合定时器确保首次执行
    function throttle(func, wait) {
      let timeStamp = 0;
      let timerId = null;

      return function (...args) {
        const context = this;
        const now = Date.now();
        const exTime = now - timeStamp;

        if (exTime >= wait) {
          if (timerId) {
            clearTimeout(timerId);
            timerId = null;
          }

          func.apply(context, args);
          timeStamp = now;
        } else if(!timerId) {
            timerId = setTimeout(() => {

                func.apply(context, args)
                timeStamp = Date.now()
                timerId = null
            }, wait - exTime)
        }
      };
    }
  </script>
  <body></body>
</html>
